export class RecurringTask {

    private immediate: boolean = false

    private interval: number = 0

    private isRunning: boolean = false

    private switch: boolean = false

    private startId: number = 0

    constructor(
        private callback: () => void,
        options: { immediate?: boolean, interval?: number } = {}
    ) {
        if (options?.immediate !== undefined) this.immediate = options.immediate
        if (options?.interval !== undefined) this.interval = options.interval
    }


    async start() {

        if (this.switch) return

        this.switch = true

        const startId = ++this.startId

        if (this.immediate) this.callback()

        while (true) {

            await new Promise(resolve => setTimeout(resolve, this.interval))

            if (
                !this.switch ||
                startId !== this.startId
            ) return

            if (this.isRunning) continue

            this.isRunning = true
            await this.callback()
            this.isRunning = false

        }
    }



    stop() {
        this.switch = false
    }

    // 单次执行
    async run() {
        if (this.isRunning) return false
        this.isRunning = true
        await this.callback()
        this.isRunning = false
        return true
    }




}